package com.xiangshizhineng.tianzhangzhi.app.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xiangshizhineng.tianzhangzhi.app.common.ResultCode;
import com.xiangshizhineng.tianzhangzhi.app.common.exception.SignException;
import com.xiangshizhineng.tianzhangzhi.app.filter.AppToken;
import com.xiangshizhineng.tianzhangzhi.app.utils.JwtUtils;
import com.xiangshizhineng.tianzhangzhi.app.utils.RedisUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @Description: 拦截器
 * @author: zhuxiaokang
 * @date:
 */
@Component
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //去掉OPTIONS 请求,否则token获取为null
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
            httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method methods = handlerMethod.getMethod();

        // 验证AppToken
        if (methods.isAnnotationPresent(AppToken.class)) {
            AppToken appToken = methods.getAnnotation(AppToken.class);
            if (appToken.required()) {
                String token = request.getHeader("Authorization");
                String tokenKey = JwtUtils.getAppTokenKey(token);
                String saveToken = (String) redisUtils.get(tokenKey);
                if (saveToken != null && token.equals(saveToken)) {
                    return true;
                } else {
//                    throw new SignException(ResultCode.Token_ERROR.getCode(), "登录失效, 请重新登录");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter out = null;
                    JSONObject res = new JSONObject();

                    res.put("message", "");
                    res.put("code", 100403);
                    out = response.getWriter();
                    System.out.println(res);
                    out.append(res.toString());
                    out.close();
                    return false;
                }
            }
        }
        return true;
    }

}
